#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include <memory>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "nocopy.hpp"

namespace socket_ns
{
    class Socket;
    using namespace log_ns;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };

    class Socket : public nocopy
    {
    public:
        virtual void CreateSocket() = 0;
        virtual void CreateBind(uint16_t port) = 0;
        virtual void CreateListen() = 0;
        virtual bool Conntecor(const std::string &peerip, uint16_t peerport) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;
        virtual int Accepter(InetAddr *addr, int *code) = 0;
        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;

    public:
        void BuildTcpServerSocket(uint16_t port)
        {
            CreateSocket();
            CreateBind(port);
            CreateListen();
        }

        bool BuildTcpClientSocket(const std::string &peerip, uint16_t peerport)
        {
            CreateSocket();
            return Conntecor(peerip, peerport);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket() {}
        TcpSocket(int sockfd) : _sockfd(sockfd) {}

        void CreateSocket() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "sockfd error\n");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "sockfd create sucess, sockfd: %d\n", _sockfd);
        }

        void CreateBind(uint16_t port) override
        {
            _port = port;
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;

            if (::bind(_sockfd, (sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "socket bind sucess\n");
        }

        void CreateListen() override
        {
            if (::listen(_sockfd, 8) < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen sucess\n");
        }

        int Accepter(InetAddr *addr, int *code)
        {
            sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_sockfd, (sockaddr *)&client, &len);
            *code = errno;
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return -1;
            }

            *addr = InetAddr(client);
            LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n",
                addr->addrStr().c_str(), sockfd);
            return sockfd;
        }

        bool Conntecor(const std::string &peerip, uint16_t peerport)
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            if (::connect(_sockfd, (sockaddr *)&server, sizeof(server)) < 0)
            {
                LOG(FATAL, "connect socket error\n");
                return false;
            }

            LOG(DEBUG, "connect socket success\n");
            return true;
        }

        int Sockfd()
        {
            return _sockfd;
        }

        void Close()
        {
            if (_sockfd > 0)
            {
                ::close(_sockfd);
            }
        }

        ssize_t Recv(std::string *out) override
        {
            char inbuffer[4096];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }

        ssize_t Send(const std::string &in)
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }

        ~TcpSocket() {}

    private:
        int _sockfd;
        uint16_t _port;
    };
};